import { DemoBlock } from '@/components/demos-util';
import { type DetailResult } from '@/pages/types/type';
import { checkAuthorize } from '@/utils/authorize';
import { Content, Page } from '@alita/flow';
import { setPageNavBar, useLocation, useNavigate } from 'alita';
import {
    Button,
    Card,
    Cascader,
    Checkbox,
    DotLoading,
    Form,
    Input,
    NavBar,
    Radio,
    Space,
    Switch,
    Toast,
} from 'antd-mobile';
import type { CascaderRef } from 'antd-mobile/es/components/cascader';
import { RefObject, useEffect, useState } from 'react';

import { getRequestInit, postRequestInit, urlPrefix } from '@/utils/http';
import { useModel } from 'alita';
import { AntOutline, RightOutline } from 'antd-mobile-icons';
import styles from './index.less';
import { WeiXinUserPicker } from '@/pages/selectors/wei-xin-user';
const numberFormator = new Intl.NumberFormat();

export default () => {
    const navigate = useNavigate();
    const location = useLocation();
    //   const [searchParams, setSearchParams] = useSearchParams();
    const [tokening, setTokening] = useState<boolean>(true);
    const [tokenFail, setTokenFail] = useState<string | undefined>(undefined);
    const [authOK, setAuthOK] = useState<boolean>(false);
    const [loadFails, setLoadFails] = useState<string[]>([]);
    const [loadOK, setLoadOK] = useState<string | undefined>(undefined);
    const [loadingTimes, setLoadingTimes] = useState<number>(0);

    // 提交时状态控制
    const [ing, setIng] = useState<boolean>();
    const [fail, setFail] = useState<string>();
    const [success, setSuccess] = useState<string>();

    const [diagnosisGroups, setDiagnosisGroups] = useState<
        {
            value: string;
            label: string;
        }[]
    >([]);

    type FieldModal = {
        staffNo: string;
        staffName: string;
    };
    const [form] = Form.useForm<FieldModal>();

    const model = useModel('useAuthModel');
    useEffect(() => {
        setPageNavBar({
            pagePath: location.pathname,
            navBar: {
                hideNavBar: true,
                pageTitle: `诊断组添加成员`,
                pageBackground: '#eee',
            },
        });
        checkAuthorize(
            (x) => setTokening(x),
            (y) => {
                console.log(`token检查完成，是否通过授权：${y}`);
                setAuthOK(y);
            },
            (z) => setTokenFail(z),
            model,
        );
    }, []);

    function load() {
        if (authOK) {
            let times = 1;
            // 加载所有诊断组
            fetch(
                `${urlPrefix}/api/diagnosis-group-handle/get-diagnosis-groups`,
                getRequestInit(),
            )
                .then(async (rsp: Response) => {
                    if (rsp.ok) {
                        await rsp
                            .json()
                            .then(
                                ({
                                    data,
                                    code,
                                    msg,
                                }: DetailResult<{ value: string; label: string }[]>) => {
                                    if (code === 0) {
                                        if (data) {
                                            setDiagnosisGroups(data!);
                                        }
                                        setLoadOK(msg);
                                    } else {
                                        setLoadFails([...loadFails, msg]);
                                    }
                                },
                            )
                            .catch((reason) => {
                                setLoadFails([...loadFails, reason]);
                            });
                    }
                })
                .catch((reason: any) => {
                    console.error(reason);
                    setLoadFails([...loadFails, `加载诊断组：${reason}`]);
                })
                .finally(() => {
                    setLoadingTimes(--times);
                });
        } // end if authOK
    }
    useEffect(load, [authOK]);

    const onFinish = (values: FieldModal) => {
        // Dialog.alert({
        //   content: <pre>{JSON.stringify(values, null, 2)}</pre>,
        // });
        // return;
        const url = '/api/diagnosis-group-handle/add-member';
        const requestInit: RequestInit = postRequestInit(values);
         setIng(true);
        let response: Promise<Response> = fetch(`${urlPrefix}${url}`, requestInit);
       
        response
            .then(async (rsp: Response) => {
                if (rsp.ok) {
                    rsp
                        .json()
                        .then(async (x: DetailResult<number>) => {
                            const { code, msg } = x;
                            if (code === 0) {
                                Toast.show({ icon: 'success', content: msg });
                            } else {
                                Toast.show({ icon: 'fail', content: msg });
                                setFail(msg);
                            }
                        })
                        .catch((reason) => {
                            setFail(reason);
                            console.error(`${url} catch in 最内层!`);
                        })
                        .finally(() => {
                            console.log(`finally in 最内层:${url}`);
                        });
                } else {
                    setFail(`rsp not OK![${url}]`);
                    console.log(`!!! rsp not ok! [${url}]`);
                }
            })
            .catch((reason: any) => {
                console.error(reason);
                setFail(`发生错误：${reason}[${url}]`);
                console.error(`${url} catch in 最外层`);
            })
            .finally(() => {
                setIng(false);
                console.log(`finally in 最外层:${url}`);
                setIng(false);
            });
    };

    if (tokening) {
        return (
            <div style={{ color: '#00b578' }}>
                <DotLoading color="currentColor" />
                <span>正在授权...</span>
            </div>
        );
    }

    if (loadingTimes > 0) {
        return (
            <div style={{ color: '#00b578' }}>
                <DotLoading color="currentColor" />
                <span>正在载入,剩余{loadingTimes}个请求...</span>
            </div>
        );
    }

    return (
        <Page>
            <Content>
                <DemoBlock padding={8}>
                    <NavBar
                        left={
                            <Button
                                color="primary"
                                size="mini"
                                shape="rounded"
                                onClick={() => navigate('/')}
                            >
                                首
                            </Button>
                        }
                        // 未定义导航栏右侧内容！
                        onBack={() => navigate(-1)}
                    >
                        新增报告或审核医生
                    </NavBar>
                </DemoBlock>

                <Card
                    title={
                        <div style={{ fontWeight: 'normal' }}>
                            <AntOutline style={{ marginRight: '4px', color: '#1677ff' }} />
                            新增报告或审核医生
                        </div>
                    }
                    extra={<RightOutline />}
                    // onBodyClick={onBodyClick}
                    // onHeaderClick={onHeaderClick}
                    style={{ borderRadius: '16px', margin: '10px' }}
                >
                    <div className={styles.content}>
                        <Form
                            form={form}
                            layout={'vertical'}
                            onFinish={onFinish}
                            footer={
                                <>
                                    <Button
                                        block
                                        type="submit"
                                        disabled={
                                            !authOK ||
                                            ing ||
                                            fail !== undefined ||
                                            success !== undefined
                                        }
                                        loading={ing}
                                        color="primary"
                                        size="large"
                                    >
                                        {success !== undefined ? '已新增' : '提交'}
                                    </Button>
                                </>
                            }
                        >
                            <WeiXinUserPicker
                                name="weiXinUser"
                                label="医生"
                                required={true}
                            />

                            <Form.Item
                                name="diagnosisGroup"
                                label={'诊断组'}
                                rules={[{ required: true, message: '诊断组' }]}
                            >
                                <Radio.Group>
                                    <Space direction={'vertical'}>
                                        {diagnosisGroups.map(({ value, label }) => (
                                            <Radio key={value} value={value}>
                                                {label}
                                            </Radio>
                                        ))}
                                    </Space>
                                </Radio.Group>
                            </Form.Item>

                            <Form.Item
                                name="standards"
                                label={'医生权限'}
                                rules={[{ required: true, message: '医生权限' }]}
                            >
                                <Checkbox.Group>
                                    <Space direction={'vertical'}>
                                        {[
                                            { id: 'writeReportDoctor', name: '报告医生' },
                                            { id: 'ratifyDoctor', name: '审核医生' },
                                        ].map(({ id, name }) => (
                                            <Checkbox key={id} value={id}>
                                                {name}
                                            </Checkbox>
                                        ))}
                                    </Space>
                                </Checkbox.Group>
                            </Form.Item>
                        </Form>
                    </div>
                </Card>
            </Content>
        </Page>
    );
};

